<?php
/**
 * Created by PhpStorm.
 * User: qdq
 * Date: 2017/3/8
 * Time: 18:29
 */

namespace app_supplier\models;


use yii\data\Pagination;

class MaterialType extends Common
{
    public static function getAllMaterialType($where, $sort=null, $order=null, $page=null, $size=null,$dealer_id, $isStoreMaterial)
    {
        if (empty($where))
            $where = '1';
        if(empty($isStoreMaterial))
            $sql = static::query()
                ->select('m.name, m.id as mid, mt.type, mt.description, mt.brand, mt.material_id, mt.format as format, mt.id as mtid, dmt.price as price,dmt.sale_price as selling_price')
                ->from('material m, material_type mt')
                ->leftJoin('(select * from dealer_material_type where dealer_id='.$dealer_id.') dmt','dmt.material_type_id=mt.id')
                ->where('mt.material_id=m.id AND mt.status=1 AND '.$where);
        else
            $sql = static::query()
                ->select('m.name, m.id as mid, mt.type, mt.description, mt.brand, mt.material_id, mt.format as format, mt.id as mtid, dmt.price as price,dmt.sale_price as selling_price')
                ->from('dealer_material_type dmt')
                ->innerJoin('material_type mt','dmt.material_type_id=mt.id')
                ->innerJoin('material m','dmt.material_id=m.id')
                ->where('dmt.dealer_id='.$dealer_id.' AND ' .$where)
                ->groupBy('dmt.id');

        if ($sort && $order) {
            if ($sort == 'type')
                $sql = $sql->orderBy(' ORDER BY mt.type '.$order);
        }

        $total = $sql->count();
        $pages = new Pagination(['totalCount' =>$total, 'pageSize' => $size]);
        $all = $sql->offset($pages->offset)->limit($pages->limit)->all();

//        if ($page && $size) {
//            $offset = ($page-1)*$size;
//            $sql = $sql->limit();
//            $sql .= " LIMIT ".$offset.",".$size;
//        }
//
//        $query = $this->db->query($sql);
//        $resData['list'] = $query->rows;
//        $resData['total'] = $total;

        return ['total'=>$total,'all'=>$all,'pages'=>$pages];
    }
}